package com.ctaa.login;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.common.pojo.dto.Result;
import com.common.utils.ConstantsUrl;
import com.common.utils.ValidationUtils;
import com.ctaa.R;
import com.ctaa.databinding.ActivityForgotPasswordBinding;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

public class ForgotPasswordActivity extends AppCompatActivity {

    private ActivityForgotPasswordBinding forgotPasswordBinding;

    private CountDownTimer countDownTimer;
    private static final long COUNT_DOWN_TIME = 60000; // 60秒
    private static final long COUNT_DOWN_INTERVAL = 1000; // 1秒间隔

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        forgotPasswordBinding = ActivityForgotPasswordBinding.inflate(getLayoutInflater());
        setContentView(forgotPasswordBinding.getRoot());

        // 初始化返回按钮
        forgotPasswordBinding.backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 返回登录页面
                onBackPressed();
                // 添加过渡动画
                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
            }
        });
        forgotPasswordBinding.sendCodeButton.setOnClickListener(v -> {

            // 这里添加发送验证码的逻辑
            sendVerificationCode();
        });
    }

    private void startCountdown() {
        // 禁用按钮，防止重复点击
        forgotPasswordBinding.sendCodeButton.setEnabled(false);

        // 创建倒计时器
        countDownTimer = new CountDownTimer(COUNT_DOWN_TIME, COUNT_DOWN_INTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                // 更新按钮文本，显示剩余秒数
                forgotPasswordBinding.sendCodeButton.setText("重新发送(" + millisUntilFinished / 1000 + "s)");
            }

            @Override
            public void onFinish() {
                // 倒计时结束，恢复按钮状态
                forgotPasswordBinding.sendCodeButton.setEnabled(true);
                forgotPasswordBinding.sendCodeButton.setText("发送验证码");
            }
        }.start();
    }

    private void sendVerificationCode() {
        // 实现发送验证码的逻辑
        // 例如：调用API发送验证码到用户邮箱
        String email = forgotPasswordBinding.emailEditText.getText().toString();
        if (email == null || "".equalsIgnoreCase(email)) {
            showToast("邮箱不能为空");
            return;
        }
        boolean validEmail = ValidationUtils.isValidEmail(email);
        if (!validEmail) {
            showToast("邮箱格式不正确");
            return;
        }
        startCountdown();
        OkHttpUtils.get().url(ConstantsUrl.forgotPasswordUrl)
                .addParams("email", email)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (e instanceof java.net.SocketTimeoutException) {
                            showToast("网络连接超时，请检查网络设置");
                        } else if (e instanceof java.io.IOException) {
                            showToast("网络请求失败，请检查网络连接");
                        } else {
                            showToast("网络请求出现未知错误");
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Result result = null;
                        try {
                            result = JSONObject.parseObject(response, Result.class);
                        } catch (Exception e) {
                        }
                        if (result == null) {
                            result = Result.fail("发送邮箱请求返回失败");
                        }
                        showToast(result.getMessage());
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 销毁Activity时停止倒计时，防止内存泄漏
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    private void showToast(String content) {
        runOnUiThread(()->{
            Toast.makeText(ForgotPasswordActivity.this, content, Toast.LENGTH_SHORT).show();
        });
    }
}